package com.glc.hms.core.interceptor;

import com.glc.hms.common.exception.ServiceException;
import com.glc.hms.core.annotation.AuthIgnore;
import com.glc.hms.system.entity.SysUserToken;
import com.glc.hms.system.service.ISysUserTokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器 用于验证接口的token
 * @author Santa
 * @since 2019/11/14
 */
@Slf4j
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private ISysUserTokenService tokenService;

    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AuthIgnore annotation;

        //规避探测性质的 OPTIONS请求
        String optionsString = "OPTIONS";
        if (optionsString.equals(request.getMethod())){
            log.info("OPTIONS 请求");
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }


        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class);
        }else{
            return true;
        }

        //如果有@IgnoreAuth注解，则不验证token
        if(annotation != null){
            return true;
        }

        // 获取其他请求头参数
        String requestURI = request.getRequestURI();
        log.info("requestURI={}",requestURI);
        String remoteHost = request.getRemoteHost();
        log.info("remoteHost={}",remoteHost);
        String pathInfo = request.getPathInfo();
        log.info("pathInfo={}",pathInfo);
        StringBuffer requestURL = request.getRequestURL();
        log.info("requestURL={}",requestURL.toString());
        String servletPath = request.getServletPath();
        log.info("servletPath={}",servletPath);





        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }

        //token为空
        if(StringUtils.isBlank(token)){
            throw new ServiceException(500,"非法请求");
        }

        //TODO 这个地方后面考虑用缓存或者redis 避免频繁查询
        //查询token信息
        SysUserToken tokenEntity = tokenService.queryByToken(token);
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new ServiceException(500,"无效token，请重新登录");
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, tokenEntity.getUserId());
        return true;
    }
}























